package com.hll.erp.config;

import com.hll.erp.entity.User;
import com.hll.erp.service.UserService;
import com.hll.erp.util.UserRoleUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author cVzhanshi
 * @since 2021-06-19 22:01
 */
public class UserRealm extends AuthorizingRealm {
  private static final transient Logger log = LoggerFactory.getLogger(UserRealm.class);
  @Autowired UserService userService;

  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    Subject subject = SecurityUtils.getSubject();
    User user = (User) subject.getPrincipal();
    // 添加权限
    UserRoleUtils.getRoles(user).forEach(info::addRole);
    return info;
  }

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
      throws AuthenticationException {
    UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
    User user = userService.findUserByName(userToken.getUsername());
    if (user == null) {
      return null;
    }
    return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
  }
}
